import { getPlayer, getPlayerLyric } from "@/http/modules/player";
import songLocal from '@/util/songlistlocalStorage.js'
import ParseLyric from '@/util/parse-lyric.js'

const { createSlice, createAsyncThunk } = require("@reduxjs/toolkit");

export const getPlayerInfo = createAsyncThunk("player",async (id)=>{
    const res = await getPlayer(id);
    return res.songs[0]
})

export const getLyricInfo = createAsyncThunk("lyric",async (id)=>{
    const res = await getPlayerLyric(id);
    return ParseLyric(res.lrc.lyric);
})

const hallSlice = createSlice({
    name:"playlist",
    initialState:{
        player:songLocal.getItem()[songLocal.getItem().length-1] || {},
        playerList:songLocal.getItem() || [],
        playerIndex:0,
        isPlay:false,
        playModel:0,
        // 0为列表循环播放，1为单曲循环播放、2为随机播放
        lyric:[],
        lyricIndex:0,
        timer:0
    },
    reducers:{
        changeIsPlay(state,action){
            state.isPlay = action.payload
        },
        changePlayerList(state,action){
            state.playerList.push(action.payload);
            songLocal.setItem(state.playerList)
            state.playerIndex = state.playerList.length-1
        },
        changeIndex(state,action){
            state.playerIndex = action.payload
        },
        changePlayModel(state,{payload}){
            state.playModel = payload
        },
        changeTimer(state,{payload}){
            state.timer = payload
            const nowLyric = state.lyric.findIndex((n)=>{
                return n.time > payload*1000
            })
            console.log(state?.lyric[nowLyric-1]?.content);
            state.lyricIndex = nowLyric-1
        }
    },
    extraReducers:{
        [getPlayerInfo.fulfilled](state,{payload}){
            state.player = payload;
        },
        [getLyricInfo.fulfilled](state,{payload}){
            state.lyric = payload
        }
    }
})

export const {changeIsPlay,changePlayerList,changeIndex,changePlayModel,changeTimer} = hallSlice.actions

export default hallSlice.reducer